import sys
from ctypes import windll

GWL_EXSTYLE = -20
WS_EX_APPWINDOW = 0x00040000
WS_EX_TOOLWINDOW = 0x00000080


class TkMove:
    def __init__(self, tk, icon):
        self.x = 0
        self.y = 0
        self.tk = tk
        self.icon = icon
        self.tk.bind("<Button-1>", self.init)
        self.tk.bind("<B1-Motion>", self.move)
        self.tk.overrideredirect(True)
        self.tk.withdraw()
        self.tk.after(1, self.move_to_center)
        self.tk.after(10, self.set_appwindow)

    def move_to_center(self):
        self.tk.update()
        new_x = (self.tk.winfo_screenwidth() - self.tk.winfo_width()) / 2
        new_y = (self.tk.winfo_screenheight() - self.tk.winfo_height()) / 2
        if new_x > self.tk.winfo_width():
            new_x = 100
        if new_y > self.tk.winfo_height():
            new_y = 100
        self.tk.geometry('%dx%d+%d+%d' % (self.tk.winfo_width(), self.tk.winfo_height(), new_x, new_y))
        self.tk.deiconify()
        if self.icon is not None:
            if getattr(sys, 'frozen', False):
                self.icon = sys._MEIPASS + '/' + self.icon
            self.tk.iconbitmap(self.icon)

    def set_appwindow(self):
        hwnd = windll.user32.GetParent(self.tk.winfo_id())
        stylew = windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
        stylew = stylew & ~WS_EX_TOOLWINDOW
        stylew = stylew | WS_EX_APPWINDOW
        windll.user32.SetWindowLongW(hwnd, GWL_EXSTYLE, stylew)
        self.tk.wm_withdraw()
        self.tk.after(10, lambda: self.tk.wm_deiconify())

    def init(self, event):
        self.x, self.y = event.x, event.y

    def move(self, event):
        new_x = (event.x - self.x) + self.tk.winfo_x()
        new_y = (event.y - self.y) + self.tk.winfo_y()
        self.tk.geometry('%dx%d+%d+%d' % (self.tk.winfo_width(), self.tk.winfo_height(), new_x, new_y))